<?php

namespace App\Models\Clickhouse\Guanyuan;

use App\Models\Clickhouse\BaseCHModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageMappingModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Service\Kms\Home\HomeService;
use App\Service\Kms\Task\UserRoleService;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Kuafu\LaravelClickHouse\Database\Eloquent\Builder;

class GyDailyDeliveryReportCHModel extends BaseCHModel
{
    protected $table = 'gy_daily_delivery_report';

    /**
     * 首页查询条件构造
     *
     * @param int $role
     * @param int $regionSelectionType
     * @param string $region
     * @return Builder
     */
    public static function buildHomeSearchQuery(int $role, int $regionSelectionType, string $region): Builder
    {
        $query = null;
        if ($role == UserRoleService::ROLE_BASE_SUPERVISOR) {
            $signOrder = OpenShopSignOrderModel::query()->whereHas("checkAcceptRel", function ($query) {
                $query->where("managerId", auth()->user()->rmsUserId);
            })->get();
            if ($signOrder->isNotEmpty()) {
                $query = function ($query) use ($signOrder) {
                    $query->whereIn("storeCode", $signOrder->pluck("shopCode")->toArray());
                };
            }
        } else {
            switch ($regionSelectionType) {
                case HomeService::REGION_SELECTION_TYPE_1:
                    $query = function ($query) use ($region) {
//                        $query->where("region", "LIKE", "%" . str_replace("分公司", "", $region) . "%");
                        $organizationModel = OpenShopOrganizationManageModel::query()
                                                                            ->with("regionRel")
                                                                            ->where("name", $region)
                                                                            ->first();

                        if($organizationModel && $organizationModel->regionRel){
                            return $query->whereIn("province", $organizationModel->regionRel->pluck("provinceName")->toArray());
                        }else{
                            return $query->where("province", "-1");
                        }
                    };
                    break;
                case HomeService::REGION_SELECTION_TYPE_2:
                    $query = function ($query) use ($region) {
                        return $query->where("province", $region);
                    };
                    break;
                case HomeService::REGION_SELECTION_TYPE_3:
                    $query = function ($query) use ($region) {
                        return $query->where("city", $region);
                    };
                    break;
                case HomeService::REGION_SELECTION_TYPE_4:
                    $query = function ($query) use ($region) {
                        $provinceNames = [];
                        $warRegionRow = OpenShopRegionManageModel::query()
                                                                 ->with([
                                                                     "regionMappingRel"     => function ($query) {
                                                                         $query->with(["organizationManageRel" => function($query){
                                                                             $query->with("regionRel");
                                                                         }]);
                                                                     }
                                                                 ])->where("name", $region)->first();

                        $warRegionRow->regionMappingRel->each(function (OpenShopRegionManageMappingModel $manageMappingModel) use (&$provinceNames) {
                            $provinceNames = array_merge(
                                $provinceNames,
                                $manageMappingModel->organizationManageRel->regionRel->pluck("provinceName")->toArray()
                            );
                        });

                        if ($provinceNames) {
                            return $query->whereIn("province", $provinceNames);
                        } else {
                            return $query->where("province", "-1");
                        }
                    };
                    break;
            }
        }

        return self::query()->when($query, function ($subQuery) use ($query) { return $subQuery->where($query); });
    }


    /**
     * 获取近*天活跃门店
     *
     * @param int $lastDays
     * @return array
     */
    public static function getActivityShopLists(int $lastDays = 7): array
    {
        return Cache::remember(
            vsprintf("%s:%s:%s", ["getActivityShopLists", date("Y-m-d"), $lastDays]),
            Carbon::now()->endOfDay()->timestamp - time(),
            function () use ($lastDays) {
                $endDate   = Carbon::now()->subDay()->format("Y-m-d");
                $startDate = Carbon::now()->subDays($lastDays + 1)->format("Y-m-d");
                return GyDailyDeliveryReportCHModel::query()
                                                   ->where("date", ">=", $startDate)
                                                   ->where("date", "<=", $endDate)
                                                   ->where('storeCode', ">", 0)
                                                   ->groupBy("storeCode")
                                                   ->select(["storeCode"])
                                                   ->get()->pluck("storeCode")->toArray();
            }
        );
    }

    /**
     * 获取门店的最近活跃时间
     * @param array $shopCodes
     * @param int $lastDays
     * @return array
     * @throws \Tinderbox\Clickhouse\Exceptions\ClientException
     */
    public static function getLastActivityDateByShopCode(array $shopCodes, int $lastDays = 7): array
    {
        $startDate = Carbon::now()->subDays($lastDays)->format("Y-m-d");

        return GyDailyDeliveryReportCHModel::query()
                                           ->where("date", ">=", $startDate)
                                           ->whereIn('storeCode', $shopCodes)
                                           ->orderBy('date', 'asc')
                                           ->select(["storeCode","date"])
                                           ->get()
                                           ->keyBy("storeCode")->toArray();
    }
}
